<?phpnamespace app\common\model;use hema\delivery\Driver as Delivery;use hema\map\Driver as MapDriver;use hema\wechat\Wxapp;use hema\wechat\Wechat;use hema\wechat\Pay as WxPay;use hema\alipay\Driver as Alipay;use think\facade\Db;use think\facade\Cache;use hema\Order as Ev;/** * 订单模型 */class Order extends BaseModel{    // 定义表名    protected $name = 'order';    // 定义主键    protected $pk = 'order_id';    // 追加字段    protected $append = [];	    /**     * 模型基类初始化    */    public static function init()    {        parent::init();        (new Ev())->listen();    }        /**     * 订单商品列表     */    public function goods()    {        return $this->hasMany('app\\common\\model\\OrderGoods','order_id');    }    /**     * 关联订单收货地址表     */    public function address()    {        return $this->hasOne('app\\common\\model\\OrderAddress','order_id','order_id');    }    /**     * 关联订单配送表     */    public function delivery()    {        return $this->hasOne('app\\common\\model\\OrderDelivery','order_id','order_id');    }    /**     * 关联评论表     */    public function comment()    {        return $this->hasOne('app\\common\\model\\Comment','order_id','order_id');    }    /**     * 关联餐桌/包间表     */    public function table()    {        return $this->belongsTo('app\\common\\model\\Table','table_id');    }    /**     * 关联用户表     */    public function user()    {        return $this->belongsTo('app\\common\\model\\User','user_id');    }    /**     * 订单来源     */    public function getSourceAttr($value)    {        $status = [10 => '自助点单', 20 => '代客点单'];        return ['text' => $status[$value], 'value' => $value];    }	    /**     * 订单类型     */    public function getOrderModeAttr($value)    {        $status = [10 => '堂食', 20 => '外卖', 30 => '打包'];        return ['text' => $status[$value], 'value' => $value];    }	    /**     * 付款方式     */    public function getPayModeAttr($value)    {        $status = ['未知','微信','余额','当面付','支付宝'];        return ['text' => $status[$value], 'value' => $value];    }    /**     * 付款状态     */    public function getPayStatusAttr($value)    {        $status = [10 => '待付款', 20 => '已付款'];        return ['text' => $status[$value], 'value' => $value];    }    /**     * 接单状态     */    public function getShopStatusAttr($value)    {        $status = [10 => '待接单', 20 => '已接单'];        return ['text' => $status[$value], 'value' => $value];    }    /**     * 配送状态     */    public function getDeliveryStatusAttr($value,$data)    {        $status = [10 => '待配送', 20 => '配送中', 30 => '已完成'];        return ['text' => $status[$value], 'value' => $value];    }        /**     * 收货状态     */     public function getReceiptStatusAttr($value,$data)    {        if($data['order_mode'] == 20){            $status = [10 => '待收货', 20 => '已收货'];        }else{            $status = [10 => '待完成', 20 => '已完成'];        }        return ['text' => $status[$value], 'value' => $value];    }    /**     * 退款状态     */     public function getRefundStatusAttr($value)    {        $status = [10 => '待退款', 20 => '已退款',30 => '退款中'];        return ['text' => $status[$value], 'value' => $value];    }    /**     * 订单状态     */    public function getOrderStatusAttr($value)    {        $status = [10 => '进行中', 20 => '被取消', 30 => '已完成', 40 => '退款'];        return ['text' => $status[$value], 'value' => $value];    }    /**     * 是否评价     */    public function getIsCmtAttr($value)    {        $status = ['待评价', '已评价'];        return ['text' => $status[$value], 'value' => $value];    }    /**     * 按照分类获取单列表     * $type 类别 all=所有 payment=待付款 comment=待评价 refund=退款/售后     */    public function getList(string $dataType='all', $user_id = 0, string $search = '')    {        // 筛选条件        $filter = [];        $user_id > 0 && $filter['user_id'] = $user_id;         $model = $this->with(['goods.image','table','comment','delivery','user'])            ->order(['order_id' => 'desc']);        //生成今天开始得时间戳       $today = strtotime(date("Y-m-d 00:00:00"));               switch ((string)$dataType) {            case 'all'; //全部                break;            case 'payment'; //待付款                $filter['pay_status'] = 10;                $filter['order_status'] = 10;                break;            case 'collection'; //待收款                $filter['pay_status'] = 10;                $filter['shop_status'] = 20;                $filter['order_status'] = 10;                break;            case 'shop';//待接单                $filter['shop_status'] = 10;                $filter['order_status'] = 10;                break;            case 'delivery';//待配送                $filter['shop_status'] = 20;                $filter['delivery_status'] = 10;                $filter['order_status'] = 10;                break;            case 'receipt';//待收货                $filter['pay_status'] = 20;                $filter['delivery_status'] = 30;                $filter['receipt_status'] = 10;                $filter['order_status'] = 10;                break;            case 'cancel';//被取消                $filter['order_status'] = 20;                break;            case 'complete';//已完成                $filter['order_status'] = 30;                break;            case 'comment';//待评价                $filter['is_cmt'] = 0;                $filter['order_status'] = 30;                break;            case 'refund';//全部退款                $filter['order_status'] = 40;                break;            case 'refund10';//待退款                $filter['refund_status'] = 10;                $filter['order_status'] = 40;                break;            case 'refund20';//已退款                $filter['refund_status'] = 20;                $filter['order_status'] = 40;                break;            case 'today';//今日订单                $model->where('create_time','>',$today);                break;            case 'old';//历史订单                $model->where('create_time','<',$today);                break;        }        return $model->where($filter)            ->paginate(['list_rows'=>15,'query' => request()->param()]);    }    /**     * 订单详情     */    public static function detail($id)    {        return self::with(['goods' => ['image', 'spec', 'goods'], 'address', 'table','delivery','user','comment'])            ->where(['order_id' => $id])            ->find();    }        /**     * 取消订单     */    public function cancel()    {        //如果已经付款 - 订单取消需要完成退款操作        if ($this->pay_status['value'] == 20){            //余额支付            if($this->pay_mode['value'] == 2){                //退回用户余额                $user = User::get($this->user_id);		        $user->money = ['inc', $this->pay_price];//增加余额		        $user->pay = ['dec', $this->pay_price];//减少消费金额		                        //会员对积分进行操作		        if($user['v']['value'] > 0){		            $score = intval($this->pay_price);		            $user->score = ['dec', $score];//减少积分		        }		        $user->save();            }            //微信支付            if($this->pay_mode['value'] == 1 and !empty($this->transaction_id)){                //原路退回                $WxPay = new WxPay();                if(!$result = $WxPay->refunds($this->transaction_id,$this->order_no,$this->pay_price,$this->pay_price,'api/notify/orderRefund','取消订单')){                    $this->error = $WxPay->getError();                    return false;                }            }            //支付宝支付            if($this->pay_mode['value'] == 4 and !empty($this->transaction_id)){                //原路退回                $aliPay = new Alipay();                if(!$result = $aliPay->tradeRefund($this->transaction_id,$this->refund_price,'取消订单')){                    $this->error = $aliPay->getError();                    return false;                }            }        }        return $this->save(['order_status' => 20]) !== false;    }         /**     * 商家接单     */    public function shopStatus()    {        //发送商家接单订阅消息        $this->sendMessage('receive',$this->order_id);        return $this->save([            'shop_status' => 20,            'shop_time' => time()        ]);    }        /**     * 确认收到用户付款（后付费用户）     */    public function collection()    {        // 开启事务        Db::startTrans();        try {            //如果该用户存在则执行下列操作，代客非会员下单不会执行            if($this->user_id > 0){                $user = User::get($this->user_id);                $user->pay = ['inc', $this->pay_price];//增加消费金额                                //会员对积分进行操作		        if($user['v']['value'] > 0){		            $score = intval($this->pay_price);		            $user->score = ['inc', $score];//减少积分		        }                $user->save();            }            $this->save([                'pay_mode' => 3,//现金，线下支付                'pay_status' => 20,                'pay_time' => time()            ]);            Db::commit();            return true;        } catch (\Exception $e) {            Db::rollback();        }        return false;    }        /**     * 设置配送状态     */    public function deliveryStatus($status)    {        if($status == 30 and $this->table_id == 0){            //堂食排号与自取发送            $this->sendMessage('take',$this->order_id);//取货提醒            Device::push('rows',$this->row_no);//叫号取餐        }        return $this->save([            'delivery_status' => $status,            'delivery_time' => time()        ]);    }        /**     * 确认完成     */    public function receipt()    {        // 开启事务        Db::startTrans();        try {            $this->save([                'receipt_status' => 20,                'receipt_time' => time(),                'order_status' => 30            ]);            Db::commit();            return true;        } catch (\Exception $e) {            Db::rollback();        }        return false;    }        /**     * 退款处理     */    public function refund($is_refund = 0)    {        if($this->refund_price > $this->pay_price){            $this->error = '退款金额不可大于实付金额';            return false;        }        //同意退款        if($is_refund==1){            // 开启事务            Db::startTrans();            try {                //余额退款                if($this->pay_mode['value'] == 2){                    $this->refundCallback();//退款成功回调                }                //微信退款处理                if($this->pay_mode['value'] == 1){                    $WxPay = new WxPay;                    if(!$result = $WxPay->refunds($this->transaction_id,$this->order_no,$this->refund_price,$this->pay_price,'api/notify/orderRefund',$this->refund_desc)){                        $this->error = $WxPay->getError();                        return false;                    }                    $this->save([                		'refund_status' => 30,//退款中                		'refund_time' => time(),                	]);                }                //支付宝退款处理                if($this->pay_mode['value'] == 4){                    $aliPay = new Alipay();                    if(!$result = $aliPay->tradeRefund($this->transaction_id,$this->refund_price,$this->refund_desc)){                        $this->error = $aliPay->getError();                        return false;                    }                    //判断退款是否成功                    if(isset($result['fund_change']) and $result['fund_change'] == 'Y'){                        $this->refundCallback();//退款成功回调                    }else{                        $this->save([                    		'refund_status' => 30,//退款中                    		'refund_time' => time(),                    	]);                    }                }                Db::commit();                //发送退款申请状态提醒订阅消息                $this->sendMessage('refund',$this->order_id);                return true;            } catch (\Exception $e) {                Db::rollback();            }            return false;        }        //拒绝退款        // 开启事务        Db::startTrans();        try {            OrderGoods::where('order_id',$this->order_id)->update([                'refund_num' => 0,                'refund_price' => 0            ]);            $this->save([                'order_status' => 10,                'refund_status' => 10,                'refund_price' => 0            ]);            //发送退款申请状态提醒订阅消息            $this->sendMessage('refund',$this->order_id,0);            Db::commit();            return true;        } catch (\Exception $e) {            Db::rollback();        }        return false;    }        /**     * 退款成功回调操作     */    public function refundCallback($refund_id='')    {        //是否启用库存		$values = Setting::getItem('goods');        if($values['is_stock'] == 1){            $stock = true;        }else{            $stock = false;        }		// 更新商品库存、销量		$GoodsModel = new Goods;		$GoodsModel->updateStockSales($this->goods,$stock,false);				//更新用户信息		$user = User::get($this->user_id);		if($this->pay_mode['value'] == 2){            $user->money = ['inc',$this->refund_price];//返回余额              }		$user->pay = ['dec', $this->refund_price];//扣减消费金额		//开通会员才有积分		if($user['v']['value'] > 0){		    $score = intval($this->refund_price);            $user->score = ['dec', $score];//扣减消费积分        }		$user->save();				// 更新订单状态		$this->save([			'refund_status' => 20,			'refund_time' => time(),			'refund_id' => $refund_id,		]);		return true;    		    }        /**     * 成功下单     */    public function successOrder()    {        //是否启用库存		$values = Setting::getItem('goods');        if($values['is_stock'] == 1){            $stock = true;        }else{            $stock = false;        }		// 更新商品库存、销量		$GoodsModel = new Goods;		$GoodsModel->updateStockSales($this->goods,$stock);				//打印订单		Device::print($this);		//发送新订单提醒		Device::push('new');//新订单提醒		//获取开通微信通知得店员		$openIds = ShopClerk::where('wx_open_id','<>','')->column('wx_open_id');		if(sizeof($openIds) > 0){    		//批量发送模板消息 - 使用公众号    		$wx = new Wechat;    		foreach($openIds as $item){    		    $wx->sendNewsOrder($item,$this->order_no,$this->pay_price);    		}		}		//商家是否自动接单		$values = Setting::getItem('order');		if($values['is_order'] == 1){			$this->shopStatus();			//外卖自动推送订单			if($this['order_mode']['value']==20){    			$delivery = Setting::getItem('delivery');    			if($delivery['is_delivery'] == 1){    				$this->waimai([    				    'company' => $delivery['company']    				]);    			}			}		}    }        /**     * 补单加单成功(堂食)     */    public function successIncOrder($order,$goods)    {        //是否启用库存		$values = Setting::getItem('goods');        if($values['is_stock'] == 1){            $stock = true;        }else{            $stock = false;        }		// 更新商品库存、销量		$GoodsModel = new Goods;		$GoodsModel->updateStockSales($goods,$stock);				$data = $this;		$data['goods'] = $goods;		$data['total_price'] = $order['order_total_price'];		$data['pay_price'] = $order['order_pay_price'];		//打印订单		Device::print($data);		//发送新订单提醒		Device::push('new');//新订单提醒		//获取开通微信通知得店员		$openIds = ShopClerk::where('wx_open_id','<>','')->column('wx_open_id');		//批量发送模板消息 - 使用公众号		$wx = new Wechat;		foreach($openIds as $item){		    $wx->sendNewsOrder($item,$this->order_no,$order['order_pay_price']);		}		return true;    }        /**     * 生成排队号     */    public static function rowNo()    {        $rowno = Cache::get('rowno','');        if(!empty($rowno)){            $rowno = (int)$rowno;            $rowno++;          }else{            $rowno = 1;        }        //有效期时间,截至到当天23:59:59        $time = strtotime(date('Y-m-d').'23:59:59')-time();        Cache::set('rowno', $rowno,$time);        $str_row_no = (string)$rowno;//10        $lan = strlen($str_row_no);        for($n=$lan;$n<4;$n++){            $str_row_no = '0'.$str_row_no;        }        return $str_row_no;    }                /**     * 获取订单分类统计     */    public function getOrderClassCount($dataType='all',$user_id=0)    {        // 筛选条件        $filter = [];        $user_id > 0 && $filter['user_id'] = $user_id;        $model = $this->order(['order_id' => 'desc']);        // 订单数据类型        switch ((string)$dataType) {            case 'all'; //全部                break;            case 'payment'; //待付款                $filter['pay_status'] = 10;                $filter['order_status'] = 10;                break;            case 'collection'; //待收款                $filter['pay_status'] = 10;                $filter['shop_status'] = 20;                $filter['order_status'] = 10;                break;            case 'shop';//待接单                $filter['shop_status'] = 10;                $filter['order_status'] = 10;                break;            case 'delivery';//待配送                $filter['shop_status'] = 20;                $filter['delivery_status'] = 10;                $filter['order_status'] = 10;                break;            case 'receipt';//待收货                $filter['pay_status'] = 20;                $filter['delivery_status'] = 30;                $filter['receipt_status'] = 10;                $filter['order_status'] = 10;                break;            case 'cancel';//被取消                $filter['order_status'] = 20;                break;            case 'complete';//已完成                $filter['order_status'] = 30;                break;            case 'comment';//待评价                $filter['is_cmt'] = 0;                $filter['order_status'] = 30;                break;            case 'refund';//全部退款                $filter['order_status'] = 40;                break;            case 'refund10';//待退款                $filter['refund_status'] = 10;                $filter['order_status'] = 40;                break;            case 'refund20';//已退款                $filter['refund_status'] = 20;                $filter['order_status'] = 40;                break;        }        return $model->where($filter)->count();    }        /**     * 根据条件统计数量     */    public static function getCount()    {        $count = array();        $count['all'] = [            'all' => self::where(['order_status'=> 30])->count(),//全部            'collection' => self::where(['order_status' => 10,'pay_status'=>10,'shop_status'=>20])->count(),//待收款            'refund10' => self::where(['order_status' => 40,'refund_status'=>10])->count(),//待退款            'shop' => self::where(['order_status' => 10,'shop_status'=>10])->count(),//待接单            'delivery' => self::where(['order_status' => 10,'delivery_status'=>10,'shop_status'=>20])->count(),//待配送        ];        //今天        $star = strtotime(date('Y-m-d 00:00:00',time()));        $count['today'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->count(),            'tang' => self::where(['order_mode'=> 10,'order_status'=> 30])->where('create_time','>',$star)->count(),            'wai' => self::where(['order_mode'=> 20,'order_status'=> 30])->where('create_time','>',$star)->count(),            'bao' => self::where(['order_mode'=> 30,'order_status'=> 30])->where('create_time','>',$star)->count(),            'refund' => self::where(['order_status' => 40,'refund_status'=> 20])->where('create_time','>',$star)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),//成交金额            'refund' => $refund_price,//退款金额        ];                //昨天        $star = strtotime("-1 day");        $end = strtotime(date('Y-m-d 00:00:00',time()));        $count['today2'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'tang' => self::where(['order_mode'=> 10,'order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'wai' => self::where(['order_mode'=> 20,'order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'bao' => self::where(['order_mode'=> 30,'order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'refund' => self::where(['order_status' => 40,'refund_status'=> 20])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today2']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //前天        $star = strtotime("-2 day");        $end = strtotime("-1 day");        $count['today3'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today3']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //-4天        $star = strtotime("-3 day");        $end = strtotime("-2 day");        $count['today4'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today4']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //-5天        $star = strtotime("-4 day");        $end = strtotime("-3 day");        $count['today5'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today5']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //-6天        $star = strtotime("-5 day");        $end = strtotime("-4 day");        $count['today6'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today6']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //-7天        $star = strtotime("-6 day");        $end = strtotime("-5 day");        $count['today7'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['today7']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //本月起至时间 - 月度统计         $end = mktime(0,0,0,date('m'),1,date('y'));         $count['month'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$end)->count(),            'tang' => self::where(['order_mode'=> 10,'order_status'=> 30])->where('create_time','>',$end)->count(),            'wai' => self::where(['order_mode'=> 20,'order_status'=> 30])->where('create_time','>',$end)->count(),            'bao' => self::where(['order_mode'=> 30,'order_status'=> 30])->where('create_time','>',$end)->count(),            'refund' => self::where(['order_status' => 40,'refund_status'=> 20])->where('create_time','>',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['month']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];                //上月开始          $star = mktime(0,0,0,date('m')-1,1,date('y'));         $count['month2'] = [            'all' => self::where(['order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'tang' => self::where(['order_mode'=> 10,'order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'wai' => self::where(['order_mode'=> 20,'order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'bao' => self::where(['order_mode'=> 30,'order_status'=> 30])->where('create_time','>',$star)->where('create_time','<',$end)->count(),            'refund' => self::where(['order_status' => 40,'refund_status'=> 20])->where('create_time','>',$star)->where('create_time','<',$end)->count(),        ];        //统计交易金额        $order_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where('order_status',30)->sum('pay_price');        $refund_order = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        $refund_price = self::where('create_time','>',$star)->where('create_time','<',$end)->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['month2']['money'] = [            'order' => $order_price + ($refund_order - $refund_price),            'refund' => $refund_price,        ];        return $count;    }        /**     * 根据时间段统计数量     */    public static function getDateCount($data)    {        // 筛选条件        $filter = [];        $count = [            'all' => self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status'=> 30])->count(),            'tang' => self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_mode'=> 10,'order_status'=> 30])->count(),            'wai' => self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_mode'=> 20,'order_status'=> 30])->count(),            'bao' => self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_mode'=> 30,'order_status'=> 30])->count(),            'refund' => self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->count(),        ];         //统计交易金额        $order_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status'=> 30])->sum('pay_price');        //已退款订单金额        $refund_order = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->sum('pay_price');        //实际退款金额        $refund_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->sum('refund_price');        $count['money'] = [            'order' => $order_price + ($refund_order - $refund_price),//成交金额            'refund' => $refund_price,//退款金额        ];                //待入账订单金额        $order10 = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where('order_status',10)->sum('pay_price');        //待退款订单金额        $refund_order = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>10])->sum('pay_price');        //待退款实际金额        $refund_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>10])->sum('refund_price');        //实际待退款金额        $count['money']['refund10'] = $refund_price;        //最终完成待入账订单金额 + （退款订单总额-实际退款金额）        $count['money']['order10'] = $order10 + ($refund_order - $refund_price);                //统计已完成实际额度 = 已完成订单+（退款订单总额-实际退款金额）        //微信支付        $order_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where('pay_mode',1)->where(['order_status'=> 30])->sum('pay_price');        $refund_order = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',1)->sum('pay_price');        $refund_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',1)->sum('refund_price');        $count['money']['weixin'] = $order_price + ($refund_order - $refund_price);                //余额支付        $order_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where('pay_mode',2)->where(['order_status'=> 30])->sum('pay_price');        $refund_order = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',2)->sum('pay_price');        $refund_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',2)->sum('refund_price');        $count['money']['wallet'] = $order_price + ($refund_order - $refund_price);                //线下支付        $order_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where('pay_mode',3)->where(['order_status'=> 30])->sum('pay_price');        $refund_order = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',3)->sum('pay_price');        $refund_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',3)->sum('refund_price');        $count['money']['offline'] = $order_price + ($refund_order - $refund_price);                //支付宝支付        $order_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where('pay_mode',4)->where(['order_status'=> 30])->sum('pay_price');        $refund_order = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',4)->sum('pay_price');        $refund_price = self::where($filter)->where('create_time','>',$data['star'])->where('create_time','<',$data['end'])->where(['order_status' => 40,'refund_status'=>20])->where('pay_mode',4)->sum('refund_price');        $count['money']['alipay'] = $order_price + ($refund_order - $refund_price);        return $count;    }        /**     * 外卖配送     */    public function waimai($data)    {        $shop = Setting::getItem('shop');        // 开启事务        Db::startTrans();        try {            if($data['company'] == 'self'){                //计算距离                $map = new MapDriver;                if($result = $map->getDistance($shop['coordinate'],$this['address']['location'])){				    $distance = $result[0]['distance'];//获取距离计算结果                }else{                    $this->error = $map->getError();                    return false;                }                if(!isset($data['shop_clerk_id'])){                    $clerk = [                        'linkman' => $shop['shop_name'],                        'phone' => $shop['phone'],                    ];                }else{                    $clerk = ShopClerk::get($data['shop_clerk_id']); //获取店员信息                }                $dev = [                    'linkman' => $clerk['linkman'],                    'phone' => $clerk['phone'],                    'price' => $this->delivery_price,//配送费用                    'distance' => $distance,//配送距离                    'delivery_status' => 30,  //已到店                    'order_no' => $this->order_no,                ];            }else{                $delivery = Setting::getItem('delivery');//获取外卖配送设置                $dv = new Delivery($data['company']);            }            //顺丰配送            if($data['company'] == 'sf'){                $user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度                $shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度                $time = time();        		$post_data = [        			'shop_id' => $delivery['sf_shop_id'],//$this->shop_id,//店铺ID        			'shop_type' => 1,//店铺ID类型 1：顺丰店铺ID ；2：接入方店铺ID        			'shop_order_id' => $this['order_no'],//商家订单号	不允许重复        			//'shop_preparation_time' => 0,//商家预计备餐时长 分钟级时间 比如: 10 分钟 则传入 10        			'order_source' => $shop['shop_name'],//订单接入来源        			'order_sequence' => '外卖'.$this['row_no'].'号',//取货序号        			'lbs_type' => 2,//坐标类型	1：百度坐标，2：高德坐标        			'order_time' => $this['pay_time'],//用户下单时间	秒级时间戳        			'is_appoint' => 0,//是否是预约单,0：非预约单；1：预约单        			//'appoint_type' => 2,//预约单类型 预约单的时候传入，1：预约单送达单；2：预约单上门单        			'expect_time' => $time + 1800,//用户期望送达时间	预约单需必传,秒级时间戳        			//'shop_expect_time' => 0,//商家期望送达时间 只在骑士备注展示，不参与骑士时效考核；秒级时间戳 或者 时间段，格式为：{timestamp},{timestamp}, 传时间段骑士可按这个时间段内进行妥投        			'is_insured' => 0,//是否保价，0：非保价；1：保价        			        			'is_person_direct' => 0,//是否是专人直送订单，0：否；1：是        			//'vehicle' => 0,//配送交通工具，默认0 0：否；1：电动车；2：小轿车        			//'four_wheeler_type' => 0,//⻋型 10 ⼩轿 ⻋、11 微⾯、12 ⼩⾯、13 中⾯、 14 ⼩厢货、15 ⼩平板、16 中货  只有vehicle = 2，⻋型字段才有效。 注：只支持物流产品=四轮车的连锁店铺        			'declared_value' => 0,//保价金额,单位：分        			'gratuity_fee' => 0,//订单小费，不传或者传0为不加小费	单位分，加小费最低不能少于100分        			'remark' => $this['message'],//订单备注        			'rider_pick_method' => 1,//物流流向	1：从门店取件送至用户,2：从用户取件送至门店        			'return_flag' => 511,	//返回字段控制标志位（二进制）	1:商品总价格，2:配送距离，4:物品重量，8:起送时间，16:期望送达时间，32:支付费用，64:实际支持金额，128:优惠卷总金额，256:结算方式,例如全部返回为填入511        			'push_time' => $time,        			'version' => 19,//文档版本号        			        			//收货人信息        			'receive' => [        				'user_name' => $this['address']['name'],//用户姓名        				'user_phone' => $this['address']['phone'],//用户电话        				'user_lng' => $user_location[1],//用户地址经度        				'user_lat' => $user_location[0],//用户地址纬度        				'user_address' => $this['address']['detail'], //用户地址        				'city_name' => $this['address']['city'] //发单城市,用来校验是否跨城；请填写城市的中文名称，如北京市        			],        			//发货店铺信息；Obj,平台级开发者需要传入        			'shop' => [        				'shop_name' => $shop['shop_name'],//店铺名称        				'shop_phone' => $shop['phone'],//店铺电话        				'shop_address' => $shop['address'],//店铺地址        				'shop_lng' => $shop_location[1],//店铺经度        				'shop_lat' => $shop_location[0]//店铺纬度		        			],        			//订单详情        			'order_detail' => [        				'total_price' => $this['pay_price']*100,//用户订单总金额（单位：分）        				'product_type' => 1, //物品类型,测试店铺请填写1，否则会造成【没有匹配的计价规则或计价规则已失效】        				'user_money' => $this['pay_price']*100, //实收用户金额（单位：分）        				'shop_money' => $this['pay_price']*100,//实付商户金额（单位：分）        				'weight_gram' => 1,//物品重量（单位：克）        				'volume_litre' => 5,//物品体积（单位：升）        				'delivery_money' => 1,//商户收取的配送费（单位：分）        				'product_num' => sizeof($this['goods']),//物品个数        				'product_type_num' => sizeof($this['goods'])//物品种类个数        			]        		];        		$product_detail = [];//商品列表详情        		foreach ($this['goods'] as $item){        			$product_detail[] = [        				'product_name' => $item['goods_name'],//物品名称        				'product_id' => $item['goods_id'],//物品ID        				'product_num' => $item['total_num'],//物品数量        				'product_price' => $item['goods_price'],//物品价格        				'product_unit' => '个',//物品单位        				'product_remark' => '',//备注        				'item_detail'=> ''//详情        			];        		}        		$post_data['order_detail']['post_data'] = $product_detail;//商品详情                if($result = $dv->addOrder($post_data)){                    $real_pay_money = (int)$result['result']['real_pay_money'];//配送费                    $real_pay_money = round($real_pay_money / 100,2); //四舍五入保留两位小数                    $dev = [                        'price' => $real_pay_money, //配送费                        'distance' => $result['result']['delivery_distance_meter'],//配送距离（单位米）                        'order_no' => $result['result']['sf_order_id'] //顺丰订单号（标准默认为int，可以设置为string）                    ];                }else{                    $this->error = $dv->getError();                    return false;                 }            }            if($data['company'] == 'dada'){                $user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度                $shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度                //$city_code = $dv->getCiytCode($shop['city']);                $post_data = [        			'shop_no' => $delivery['dada_shop_id'],//是 门店编号        			'origin_id' => $this['order_no'],//是 第三方订单ID        			//'city_code' => $city_code,//是 订单所在城市的code        			'cargo_price' => $this['pay_price'],//是 订单金额        			'is_prepay' => 0,//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)        			'receiver_name' => $this['address']['name'],//是 收货人姓名        			'receiver_address' => $this['address']['detail'],//是 收货人地址        			'callback' => base_url() . 'api/delivery/dada',//是 回调URL        			'receiver_lat' => $user_location[0], //否 收货人地址纬度        			'receiver_lng' => $user_location[1],//否 收货人地址经度        			'receiver_phone' => $this['address']['phone'],//否 收货人手机号        			//'tips' => 0,//否 小费（单位：元，精确小数点后一位）        			'info' => $this['message'],//否 订单备注        			//'cargo_type' => 1,//否 订单商品类型：食品小吃-1,饮料-2,鲜花-3,文印票务-8,便利店-9,水果生鲜-13,同城电商-19, 医药-20,蛋糕-21,酒品-24,小商品市场-25,服装-26,汽修零配-27,数码-28,小龙虾-29,火锅-51,其他-5        			'cargo_weight' => 0.1,//是	订单重量（单位：Kg）        			//'origin_mark_no' => '河马云店',//否	订单来源编号        			//'is_use_insurance' => 0,//是否使用保价费（0：不使用保价，1：使用保价； 同时，请确保填写了订单金额（cargo_price））	        		];                if($pre = $dv->preOrder($post_data)){                    if($result = $dv->addOrder(['delivery_no' => $pre['dada']['result']['deliveryNo']])){                        $dev = [                            'price' => $pre['dada']['result']['fee'], //配送费                            'distance' => (int)$pre['dada']['result']['distance'],//配送距离                            'order_no' => $pre['dada']['result']['deliveryNo'] //达达单号                        ];                    }else{                        $this->error = $dv->getError();                        return false;                    }                }else{                    $this->error = $dv->getError();                    return false;                 }             }            if($data['company'] == 'uu'){                $user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度                $user_location = gcj02_to_bd09($user_location[0],$user_location[1]);//腾讯坐标系转百度坐标系                $shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度                $shop_location = gcj02_to_bd09($shop_location[0],$shop_location[1]);//腾讯坐标系转百度坐标系                                $post_data = [                    'storeNo' => $delivery['uu_shop_id'],//是 门店编号        			'originId' => $this['order_id'],//第三方对接平台订单id        			'sendType' => 'SEND',//订单小类 SEND:帮我送 BUY:帮我买 TAKE:帮我取 QUEUE:代排队 NEAR_BUY:就近买        			'toAddress' => $this['address']['detail'],//目的地址        			//'toUserNote' => '',//目的地址具体门牌号(可为空)        			'toLat' => $user_location['lat'],//目的地坐标纬度，如果无，传0(坐标系为百度地图坐标系)        			'toLng' => $user_location['lon'],//目的地坐标经度，如果无，传0(坐标系为百度地图坐标系)        			//'subscribeType' => 'REAL_TIME',//预约类型(默认实时) REAL_TIME:实时订单 PICKUP_TIME:预约取件时间:DELIVERY_TIME:预约送达时间        			//'subscribeTime' => '',//预约时间时间戳（秒级）        			'goodsType' => 'FOOD',//物品类型 CAKE:蛋糕 FOOD:美食 KEY:钥匙 PHONE:手机 FILE:文件 FLOWER:鲜花 OTHER:其他        			'goodsWeight' => 1,//货物重量（单位KG）        			//'goodsPrice' => 20,//商品保价，价格（1-10000）按照一定费率收取保价费用（单位元）        			//'onlineFee' => 0,//下单额外支付小费（单位元）        			//'serviceCode' => 'UUZC',//UU服务编码 UUZC:UU专送服务 UUJJS:UU加急送服务        		];                if($pre = $dv->preOrder($post_data)){            		$post_data = [                        'storeNo' => $delivery['uu_shop_id'],//是 门店编号                        'priceToken' => $pre['uu']['priceToken'],//金额令牌，计算订单价格接口返回的price_token                        'receiver' => $this['address']['name'],//收件人                        'receiverPhone' => $this['address']['phone'],//收件人电话 手机号码；虚拟号码格式（手机号_分机号码）例如：13700000000_1111                        'note' => $this['message'],//备注                        'specialType' => 'NEED_WARM',//是否需要保温箱 NEED_WARM:需要保温箱 NOT_NEED_WARM:不需要保温箱                        'payType' => 'BALANCE_PAY',//支付方式 BALANCE_PAY:账户余额支付 ENTERPRISE_PAY:企业支付                        'orderSource' => 'OTHER',//订单来源，默认其他  MEITUAN:美团 ELEME:饿了么 OTHER:其他 DOUYIN:抖音 WEIXIN:微信                        //'shortOrderNum' => '',//订单平台短单号（0-10000），该单号会展示给骑手突出展示：“美团 #1”                        //'shopExpectTime' => 0,//商家期望送达时间时间戳(秒级)                        'callbackUrl' => base_url() . 'api/delivery/uu',//订单提交成功后及状态变化的回调地址                        'pushType' => 'OPEN_ORDER',//推送方式，默认开放订单 OPEN_ORDER:开放订单 TEST_ORDER:测试订单            		];                    if($result = $dv->addOrder($post_data)){                        $dev = [                            'price' => $pre['uu']['needPayMoney'], //配送费                            'distance' => $pre['uu']['distance'],  //配送距离                            'order_no' => $result['orderCode']                        ];                    }else{                        $this->error = $dv->getError();                        return false;                    }                }else{                    $this->error = $dv->getError();                    return false;                }             }            if($data['company'] == 'make'){                $post_data = [        			'fromcoord' => $shop['coordinate'],//起点地址坐标                    'tocoord' => $this['address']['location'],//终点地址坐标                    'shop_id' => $delivery['make_shop_id'] //店铺ID	        		];                if($pre = $dv->preOrder($post_data)){                    //附加数据json格式，回调返回该参数            		$attach = [            			'name' => $shop['shop_name']            		];            		$post_data = [            			'shop_id' => $delivery['make_shop_id'],//$this->shop_id,//店铺ID            			'goods_name' => $shop['shop_name'],//商品名称            			'order_no' => $this['order_no'],//商家订单号	不允许重复            			'notify_url' => base_url() . 'api/delivery/make',//回调地址            			'pay_price' => $pre['make']['data']['total_price'],//跑腿支付金额            			'total_price' => $pre['make']['data']['total_price'],//跑腿总金额            			'pick_time' => date("Y-m-d H:i",time()),//取件时间 格式2020-09-30 00:00            			'remark' => $this['message'],//订单备注            			'attach' => json_encode($attach,JSON_UNESCAPED_UNICODE),            		];            		$user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度                    $shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度            		//地址信息            		$address = [            			'begin_detail' => $shop['address'],            			'begin_address' => $shop['province'] . $shop['city'] . $shop['district'] . $shop['address'],            			'begin_lat' => $shop_location[0],            			'begin_lng' => $shop_location[1],            			'begin_username' => $shop['linkman'],            			'begin_phone' => $shop['phone'],            			'end_detail' => $this['address']['detail'],            			'end_address' => $this['address']['province'] . $this['address']['city'] . $this['address']['district'] . $this['address']['detail'],            			'end_lat' => $user_location[0],            			'end_lng' => $user_location[1],            			'end_username' => $this['address']['name'],            			'end_phone' => $this['address']['phone']            		];            		$post_data['address'] = json_encode($address,JSON_UNESCAPED_UNICODE);            		//商品详情            		$goods = [];            		foreach ($this['goods'] as $vo) {            			$goods[] = [            				'name' => $vo['goods_name'],//物品名称            				'price' => $vo['goods_price'],//物品价格            				'num' => $vo['total_num'],//物品数量            			];            		}            		$post_data['goods'] = json_encode($goods,JSON_UNESCAPED_UNICODE);                    if($result = $dv->addOrder($post_data)){                        $dev = [                            'price' => $pre['make']['data']['total_price'], //配送费                            'distance' => $pre['make']['data']['distance'] * 1000,//配送距离                            'order_no' => $result['data']['order_number']                        ];                    }else{                        $this->error = $dv->getError();                        return false;                    }                }else{                    $this->error = $dv->getError();                    return false;                 }             }            if($data['company'] == 'shansong'){            	$user_location = explode(',',$this['address']['location']);//拆分收货人定位经纬度                $shop_location = explode(',',$shop['coordinate']);//拆分门店定位经纬度                $post_data = [        			'cityName' => $shop['city'],//城市名称                    'appointType' => 0,//预约类型Integer	0立即单，1预约单                    //'appointmentDate' => '2020-02-02 22:00',//预约时间String 预约取件时间,只支持一个小时以后两天以内					//'deliveryType' => 1,//Integer(1) 1.帮我送 2.帮我取 ；默认为1					'lbsType' => 1,//坐标类型 0：百度坐标系，1：国测局标准坐标系，默认为0					'storeId' => $delivery['shansong_shop_id'],//店铺ID，长整类型                    'sender' => [//寄件人信息                        'fromAddress' => $shop['district'],//寄件地址                        'fromAddressDetail' =>  $shop['address'],//寄件详细地址	                        'fromSenderName' =>	$shop['shop_name'],       //寄件人姓名	                        'fromMobile' =>	$shop['phone'],//寄件人电话，支持11位手机号;支持座机号(格式：010-12345678)                        'fromLatitude' => $shop_location[0],//寄件纬度,只支持百度坐标系                        'fromLongitude' => $shop_location[1]//寄件经度,只支持百度坐标系                    ],                    'receiverList' => [//收件人信息                        'orderNo' => $this['order_no'],	//第三方平台流水号	                        'toAddress' => $this['address']['district'],//收件地址	                        'toAddressDetail' => $this['address']['detail'],//收件详细地址	                        'toLatitude' => $user_location[0],//收件纬度,只支持百度坐标系                        'toLongitude' => $user_location[1],//收件经度,只支持百度坐标系                        'toReceiverName' => $this['address']['name'],//收件人姓名	                        'toMobile' => $this['address']['phone'],//收件联系人,支持11位手机号；支持座机号格式：010-12345678                        'goodType' => 6,//	物品类型,6=餐饮                        'weight' =>1,//物品重量，单位为kg                        'remarks' => empty($this['message'])?'无':$this['message'],//备注	                    ]        		];                if($pre = $dv->preOrder($post_data)){                    $total_price = $pre['shansong']['totalFeeAfterSave']*100;//配送费用            		$post_data = [            		    'issOrderNo' => $pre['shansong']['orderNumber'],            		    'storeId' => $delivery['shansong_shop_id'],//店铺ID，长整类型            		];                    if($result = $dv->addOrder($post_data)){                        $dev = [                            'price' => $total_price, //配送费                            'distance' => $pre['shansong']['totalDistance'],//配送距离                            'order_no' => $result['orderNumber']                        ];                    }else{                        $this->error = $dv->getError();                        return false;                    }                }else{                    $this->error = $dv->getError();                    return false;                 }             }            //河马跑腿            if($data['company'] == 'hmpt'){        		$post_data = [                   'shop_id' => $delivery['hmpt_shop_id'],//（必填）门店ID                   'shop_order_no' => $this['order_no'],//（可选）第三方订单号，默认为空                   'start_time' => 0,//（可选）起送时间戳，默认0=立即                   'sequence' => $this['row_no'],//（可选）取货编号，默认为空                   'goods' => [//物品信息                        'name' => '美食',//（必填）物品名称                        'weight' => 0,//（可选）物品重量,默认0，单位公斤                        'is_incubator' => 1,//（可选）是否需要保温箱，默认0=否，1=是                        'is_insured' => 0,//（可选）是否保价，默认0=否，1=是                        'price' => 0,//（可选）物品价值，单位元，如开启保价此项必填                    ],                    'address' => [                        'user_name' => $this['address']['name'],//（必填）收货人姓名                        'user_gender' => $this['address']['gender']['value'],//（必填）性别,默认0=未知 1=先生 2=女士                        'user_phone' => $this['address']['phone'],//（必填）手机号码                        'user_lat_lng' => $this['address']['location'],//（必填）未知坐标                        'user_city' => $this['address']['city'],//（必填）城市                        'user_district' => $this['address']['district'],//（必填）区县                        'user_address' => $this['address']['detail'],//（必填）详细地址(小区门牌)                      ]                ];                if($pre = $dv->preOrder($post_data)){                    $total_price = $pre['delivery_price'];//配送费用            		$post_data = [            		    'order_no' => $pre['delivery_no']            		];                    if($result = $dv->addOrder($post_data)){                        $dev = [                            'price' => $result['pay_price'], //配送费                            'distance' => $result['distance'],//配送距离                            'order_no' => $result['order_no'],//河马跑腿平台订单号                        ];                    }else{                        $this->error = $dv->getError();                        return false;                    }                }else{                    $this->error = $dv->getError();                    return false;                 }             }                        $dev['company'] = $data['company'];            $dev['delivery_time'] = time();                        $this->delivery()->save($dev);            $this->save([                'delivery_time' => time(),                'delivery_status' => 20            ]);            Db::commit();            if($data['company'] == 'self'){                //骑手接单提醒                $this->sendMessage('horseman',$this->order_id);            }            return true;        } catch (\Exception $e) {            Db::rollback();        }        return false;    }        /**     * 取消已经推送的外卖订单     */    public function cancelDelivery()    {        //取消第三方配送单        if($this->delivery['company']['value'] != 'self'){            $dv = new Delivery($this->delivery['company']['value']);            $post_data['order_no'] = $this->delivery['order_no'];//第三方订单号            //闪送            if($this->delivery['company']['value']=='shansong'){                $delivery = Setting::getItem('delivery');//获取外卖配送设置                $post_data['shansong_shop_id'] = $delivery['shansong_shop_id'];            }            if(!$result = $dv->cancelOrder($post_data)){                $this->error = $dv->getError();                return false;            }        }         // 开启事务        Db::startTrans();        try {            OrderDelivery::where('order_delivery_id',$this->delivery['order_delivery_id'])->delete();            $this->save([                'delivery_status' => 10,                'delivery_time' => time()            ]);            Db::commit();            return true;        } catch (\Exception $e) {            Db::rollback();        }        return false;    }        /**     * 设置配送状态 - 用于外卖     */    public function setDeliveryStatus($status)    {        $delivery = [            'delivery_status' => $status,            'delivery_time' => time()        ];        if($status == 40){            $this->sendMessage('delivery',$this->order_id);//骑手配送订阅消息        }        //配送完成        if($status == 50){            $delivery['status'] = 30;            $this->save([                'delivery_status' => 30,                'delivery_time' => time()            ]);        }        return $this->delivery->save($delivery);    }        /**     * 清除订单记录     */    public function remove()    {        $filter['order_id'] = $this->order_id;        // 开启事务        Db::startTrans();        try {            $this->where($filter)->delete();            OrderAddress::where($filter)->delete();            OrderDelivery::where($filter)->delete();            OrderGoods::where($filter)->delete();            Db::commit();            return true;        } catch (\Exception $e) {            Db::rollback();        }        return false;    }        /**     * 发送订阅消息     * @param  string $type receive=商家接单通知 horseman=骑手取货通知 delivery=订单配送通知 take=取餐提醒 refund=退款状态通知     * @param  [type] $order 订单     */    public function sendMessage($type,$order_id,$is_refund=1)    {        //获取订阅消息配置        $order = Order::detail($order_id);        //判断用户是否存在（代客下单不回发送订阅消息）        if(!isset($order['user']['open_id']) or empty($order['user']['open_id'])){            return true;        }        //获取订阅消息配置        $values = Setting::getItem('wxapptpl');        $data = [];        $template_id = '';        $shop = Setting::getItem('shop');        //商家接单通知        if($type=='receive' AND !empty($values['receive'])){            $template_id = trim($values['receive']);            $data = [                'thing1' => [                    'value' => $shop['shop_name']//商家名称                ],                'thing2' => [                    'value' => '商家已接单'//订单状态                ],                'time3' => [                    'value' =>  date('Y-m-d h:i',time())//接单时间                ]            ];        }        //骑手接单通知        if($type=='horseman' AND !empty($values['horseman'])){            $template_id = trim($values['horseman']);            $data = [                'thing1' => [                    'value' => $shop['shop_name']//商家名称                ],                'thing2' => [                    'value' => '骑手正赶往商家' //订单状态                ],                'time3' => [                    'value' => date('Y-m-d h:i',time())//接单时间                ]            ];        }        //提货通知        if($type=='take' AND !empty($values['take'])){            $template_id = trim($values['take']);            $data = [                'thing3' => [                    'value' => $shop['shop_name']//提货门店                ],                'phrase2' => [                    'value' => '待用户自取'//状态                ],                'character_string6' => [                    'value' => $order['row_no'] //提货码                ],                'thing9' => [                    'value' => $shop['address'] //提货地点                ],                'phone_number7' => [                    'value' => $shop['phone'] //联系电话                ]            ];        }        //订单配送通知        if($type=='delivery' AND !empty($values['delivery'])){            $template_id = trim($values['delivery']);            $data = [                'thing8' => [                    'value' => $shop['shop_name']//商家名称                ],                'thing9' => [                    'value' => '骑手正在配送中'//订单状态                ],                'thing5' => [                    'value' => $order['delivery']['linkman'] //配送人                ],                'phone_number6' => [                    'value' => $order['delivery']['phone'] //配送电话                ],                'time10' => [                    'value' => date('Y-m-d h:i',time()) //送出时间                ]            ];        }        //退款状态通知        if($type=='refund' AND !empty($values['refund'])){            $template_id = trim($values['refund']);            if($is_refund == 1){                $status = '退款成功';                $msg = '账款将于1个工作日内原路返还';            }else{                $status = '退款失败';                $msg = '商家拒绝了您的退款请求';            }            $data = [                'character_string8' => [                    'value' => $order['order_no']//订单编号                ],                'amount9' => [                    'value' => '￥'.$order['refund_price'].'元'//退款金额                ],                'phrase4' => [                    'value' => $status //退款状态                ],                'thing5' => [                    'value' => $msg //备注                ]            ];        }        //发送订阅消息        if(sizeof($data) > 0 AND !empty($template_id)){            $wx = new Wxapp;            $queryarr = [                'touser' => $order['user']['open_id'],                'template_id' => $template_id,                'page' => 'pages/order/detail?id='.$order_id,                'data' => $data            ];            $wx->sendMessage($queryarr);        }        return true;    }    }